<template>
  <div class="list-print">
    <je-panel v-bind="printData.panelOptions">
      <template #top>
        <div class="print-top">
          <je-form
            layout="inline"
            :colon="false"
            autocomplete="off"
            style="
              width: 100%;
              height: 40px;
              padding: 2px 0 2px 20px;
              display: flex;
              justify-content: space-between;
              background: #f7f9fc;
              border-bottom: 1px solid #e6e6e6;
            "
          >
            <div
              style="
                overflow-x: scroll;
                display: flex;
                width: 70%;
                height: 40px;
                justify-content: space-between;
                align-items: center;
              "
            >
              <je-form-item label="纸张" :colon="false" name="pageType">
                <je-select
                  v-model:value="modelRef.pageType"
                  style="width: 100px"
                  @change="changePageSize"
                >
                  <je-select-option
                    v-for="item in printData.paperData"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </je-select-option>
                </je-select>
              </je-form-item>
              <je-form-item name="autoHeader" label="自动封头">
                <je-switch v-model:value="modelRef.autoHeader" mode="checkbox" />
              </je-form-item>
              <je-form-item label="每页条数" :colon="false" name="pageSize">
                <je-input-number
                  v-model:value="modelRef.pageSize"
                  :min="printData.minNum"
                ></je-input-number>
              </je-form-item>
              <je-form-item label="单行高" :colon="false" name="rowHeight">
                <je-input-number
                  v-model:value="modelRef.rowHeight"
                  :min="printData.minNum"
                ></je-input-number>
              </je-form-item>

              <je-form-item label="字体大小" :colon="false" name="fontSize">
                <je-input-number
                  v-model:value="modelRef.fontSize"
                  :min="printData.minNum"
                  style="width: 80px"
                ></je-input-number>
              </je-form-item>

              <je-button type="text" @click="importColumn"
                ><template #icon> <i class="fal fa-file-import" /> </template>导入字段</je-button
              >
              <je-dropdown v-model:visible="visible" :trigger="['click']">
                <je-button type="text">字段调整<i class="fal fa-angle-down"></i></je-button>
                <template #overlay>
                  <je-menu style="max-height: 500px; overflow: auto">
                    <je-menu-item
                      v-for="item in printData.tableColumn"
                      :key="item.field"
                      @click="clickMenuItem(item)"
                    >
                      <a href="javascript:;"
                        ><i
                          class="jeicon jeicon-check-circle-s"
                          :style="`color: ${
                            item.checked ? '#8CBC5F' : '#D7D7D7'
                          };margin-right:7px;`"
                        ></i
                        >{{ item.title }}</a
                      >
                    </je-menu-item>
                  </je-menu>
                </template>
              </je-dropdown>
              <je-button type="text" @click="fillPaper"
                ><template #icon> <i class="fal fa-arrows-h" /> </template>自动填充纸张</je-button
              >
            </div>
            <div style="width: 30%; overflow-x: scroll; display: flex; justify-content: flex-end">
              <je-form-item name="enablePrint" label="启用">
                <je-switch v-model:value="modelRef.enablePrint" mode="checkbox" />

                <je-button type="text" @click="doPreview"
                  ><template #icon><i class="jeicon jeicon-eye"></i></template>预览</je-button
                >
                <je-button type="text" @click="doSave">
                  <template #icon><i class="fal fa-save"></i></template>保存</je-button
                >
              </je-form-item>
            </div>
          </je-form>
          <je-form
            layout="inline"
            autocomplete="off"
            :colon="false"
            style="height: 40px; padding: 4px 0 2px 20px"
          >
            <je-form-item label="页眉" :colon="false" name="header">
              <je-input v-model:value="modelRef.header" style="width: 240px">
                <template #addonAfter>
                  <div style="color: #3265f5; cursor: pointer" @click="openEditorModal('header')"
                    >高级</div
                  >
                </template>
              </je-input>
            </je-form-item>
            <je-form-item label="位置" :colon="false" name="headerAlign">
              <je-radio-group v-model:value="modelRef.headerAlign" :options="printData.placeList" />
            </je-form-item>
          </je-form>
        </div>
      </template>
      <template #default>
        <div class="print-default">
          <div class="print-default-view" :style="`width:${printData.viewData.width}px`">
            <div
              class="print-header"
              :style="`text-align:${modelRef.headerAlign}`"
              v-html="`${modelRef.header ? modelRef.header : '页眉'}`"
            ></div>
            <div style="border-top: 1px dashed #e6e6e6; border-bottom: 1px dashed #e6e6e6">
              <div class="print-table">
                <div v-if="printData.showColumn.length > 0">
                  <je-table
                    ref="xTable"
                    class="print"
                    border
                    keep-source
                    resizable
                    :auto-resize="true"
                    show-header-overflow="ellipsis"
                    header-align="center"
                    :data="printTableData"
                    style="overflow-x: scroll"
                    size="mini"
                  >
                    <je-column
                      v-for="data in printData.showColumn"
                      :key="data.field"
                      :width="data.width"
                      :field="data.field"
                      :title="data.title"
                    >
                    </je-column>
                  </je-table>
                </div>
              </div>
            </div>
            <div
              class="print-fotter"
              :style="`text-align:${modelRef.fotterAlign}`"
              v-html="`${modelRef.fotter ? modelRef.fotter : '页脚'}`"
            ></div>
            <div class="print-pixel" style="width: 200mm"></div>
          </div>
        </div>
      </template>
      <template #bottom>
        <div class="print-bottom">
          <je-form layout="inline" autocomplete="off">
            <je-row
              style="width: 100%; height: 40px; padding: 4px 18px; border-bottom: 1px solid #e6e6e6"
            >
              <je-col :span="5">
                <je-form-item label="页脚" :colon="false">
                  <je-input v-model:value="modelRef.fotter">
                    <template #addonAfter>
                      <div
                        style="color: #3265f5; cursor: pointer"
                        @click="openEditorModal('fotter')"
                        >高级
                      </div>
                    </template>
                  </je-input>
                </je-form-item>
              </je-col>
              <je-col :span="5">
                <je-form-item label="位置" :colon="false">
                  <je-radio-group
                    v-model:value="modelRef.fotterAlign"
                    :options="printData.placeList"
                  />
                </je-form-item>
              </je-col>
            </je-row>
          </je-form>
          <div class="print-bottom-context">
            页眉页脚的动态参数：pageNum(页码),totalNum(总页数)；用法：第{pageNum}页/共{totalNum}页
          </div>
        </div>
      </template>
    </je-panel>
    <ModalEditorHtml
      v-if="printData.editorShow == 'editorHtml'"
      :editor-value="printData.editorValue"
      @closeModal="closeModal"
    />
    <ModalPreview
      v-if="printData.editorShow == 'preview'"
      :preview-data="printData.previewData"
      @closeModal="closeModal"
    />
  </div>
</template>

<script>
  import { ref, defineComponent, reactive, onMounted } from 'vue';
  import { Row, Col } from 'ant-design-vue';
  import {
    Button,
    Input,
    Select,
    // Checkbox,
    InputNumber,
    Radio,
    Panel,
    Form,
    Grid,
    Modal,
    Dropdown,
    Menu,
    Switch,
  } from '@jecloud/ui';
  import { ListFieldConfigGet, doUpdateHelp, ListItemCustomGetDetail } from '@/api/index';

  import ModalEditorHtml from './modal-editor-html.vue';

  import ModalPreview from './modal-preview.vue';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'ListPrint',
    components: {
      JePanel: Panel,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeRow: Row,
      JeCol: Col,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      // JeCheckbox: Checkbox,
      JeInputNumber: InputNumber,
      JeInput: Input,
      JeButton: Button,
      JeRadioGroup: Radio.Group,
      JeTable: Grid,
      JeColumn: Grid.Column,
      ModalEditorHtml,
      ModalPreview,
      JeDropdown: Dropdown,
      JeMenu: Menu,
      JeMenuItem: Menu.Item,
      JeSwitch: Switch,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['changeRecord'],
    setup(props, { emit }) {
      const xTable = ref(null);
      const modelRef = reactive({
        pageType: '210*297',
        autoHeader: true,
        pageSize: 30,
        rowHeight: 30,
        fontSize: 12,
        enablePrint: false,
        header: '',
        headerAlign: 'left',
        fotter: '',
        fotterAlign: 'left',
      });
      const printData = reactive({
        minNum: 0,
        panelOptions: { top: { size: 80 }, bottom: { size: 80 } },
        placeList: [
          { value: 'left', label: '左' },
          { value: 'center', label: '中' },
          { value: 'right', label: '右' },
        ],
        paperData: [
          { value: '210*297', label: 'A4' },
          { value: '297*420', label: 'A3' },
          { value: '148*210', label: 'A5' },
          { value: '182*257', label: 'B5' },
          { value: '297*210', label: '横版A4' },
          { value: '420*297', label: '横版A3' },
          { value: '210*148', label: '横版A5' },
          { value: '257*182', label: '横版B5' },
        ],
        editorShow: false,
        editorValue: { value: '', title: '', type: '' },
        tableColumn: [],
        showColumn: [],
        viewData: {
          width: 900,
          headerText: modelRef.header != '' ? modelRef.header : '页眉',
          fotterText: modelRef.fotter != '' ? modelRef.fotter : '页脚',
        },
        previewData: {},
      });

      const rulesRef = reactive({});
      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });

      onMounted(() => {
        getPrintData();
      });

      //加载初始化数据
      const getPrintData = () => {
        ListItemCustomGetDetail({
          tableCode: 'JE_CORE_FUNCINFO',
          pkValue: props.recordData.id,
        })
          .then((obj) => {
            if (obj && obj.FUNCINFO_GRIDPRINTINFO && obj.FUNCINFO_GRIDPRINTINFO != '') {
              const info = JSON.parse(obj.FUNCINFO_GRIDPRINTINFO);
              modelRef.pageType = info.pageType;
              modelRef.autoHeader = info.autoHeader;
              modelRef.pageSize = info.pageSize;
              modelRef.rowHeight = info.rowHeight;
              modelRef.fontSize = info.fontSize;
              modelRef.enablePrint = info.enablePrint;
              modelRef.header = info.header;
              modelRef.headerAlign = info.headerAlign;
              modelRef.fotter = info.fotter;
              modelRef.fotterAlign = info.fotterAlign;

              // showColumn.value = info.relColumns;
              printData.showColumn = info.relColumns;
              console.log(info.relColumns);
            }
            getColumns();
            changePageSize();
          })
          .catch((error) => {
            Modal.alert(error.message, 'error');
          });
      };

      //打开编辑器
      const openEditorModal = (type) => {
        printData.editorValue.type = type;
        printData.editorValue.value = modelRef[type];
        printData.editorValue.title = type == 'header' ? '页眉' : '页脚';
        printData.editorShow = 'editorHtml';
      };

      //编辑器面板关闭回调
      const closeModal = (obj) => {
        if (obj.type == 'ok') {
          modelRef[printData.editorValue.type] = obj.value;
        }
        printData.editorShow = false;
      };

      //改变纸张大小
      const changePageSize = () => {
        const width = modelRef.pageType.split('*')[0];
        const doc = document
          .getElementsByClassName('list-print')[0]
          .getElementsByClassName('print-pixel')[0];
        doc.style.width = width + 'mm';
        printData.viewData.width = doc.clientWidth;
      };

      //获得表单列信息
      const getColumns = () => {
        const params = {
          tableCode: 'JE_CORE_RESOURCECOLUMN',
          funcId: props.recordData.id,
          j_query: JSON.stringify({
            custom: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: props.recordData.id,
                type: '=',
                cn: 'and',
              },
            ],
            order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
          }),
        };
        ListFieldConfigGet(params)
          .then((res) => {
            const rows = res.data.rows;
            const columns = [];
            if (rows && rows.length > 0) {
              rows.forEach((item) => {
                let checked = false;
                let width = item.RESOURCECOLUMN_WIDTH;
                printData.showColumn.forEach((col) => {
                  if (item.RESOURCECOLUMN_CODE == col.field) {
                    checked = true;
                    width = col.width;
                  }
                });
                columns.push({
                  field: item.RESOURCECOLUMN_CODE,
                  width,
                  show: item.RESOURCECOLUMN_HIDDEN != '1',
                  checked,
                  title: item.RESOURCECOLUMN_NAME,
                });
              });
              printData.tableColumn = columns;
            }
          })
          .catch((error) => {
            Modal.alert(error.message, 'error');
          });
      };

      //导入字段
      const printTableData = ref();
      const showColumn = ref([]);
      const importColumn = () => {
        // showColumn.value = [];
        printData.showColumn = [];
        const column = [];
        printData.tableColumn.forEach((item) => {
          if (item.show) {
            item.checked = true;
            column.push(item);
          } else {
            item.checked = false;
          }
        });
        if (column.length > 0) {
          // showColumn.value = column;
          printData.showColumn = column;
          console.log('data', printData.showColumn);
        }
      };

      //保存数据
      const doSave = () => {
        const info = JSON.parse(JSON.stringify(modelRef));
        if (xTable.value == null) {
          return Modal.alert('请导入字段！', 'error');
        }
        const columns = xTable.value.getColumns();
        if (columns.length <= 0) {
          return Modal.alert('请导入字段！', 'error');
        }
        const relColumns = [];
        columns.forEach((item) => {
          relColumns.push({ field: item.field, width: item.renderWidth, title: item.title });
        });
        info.relColumns = relColumns;
        doUpdateHelp({
          tableCode: 'JE_CORE_FUNCINFO',
          JE_CORE_FUNCINFO_ID: props.recordData.id,
          FUNCINFO_GRIDPRINTINFO: JSON.stringify(info),
        })
          .then((res) => {
            Modal.message(res.message, 'success');
          })
          .catch((error) => {
            Modal.alert(error.message, 'error');
          });
      };

      //预览
      const doPreview = () => {
        const info = JSON.parse(JSON.stringify(modelRef));
        if (xTable.value == null) {
          return Modal.alert('请导入字段！', 'error');
        }
        const columns = xTable.value.getColumns();
        if (columns.length <= 0) {
          return Modal.alert('请导入字段！', 'error');
        }
        const relColumns = [];
        columns.forEach((item) => {
          relColumns.push({ field: item.field, width: item.renderWidth, title: item.title });
        });
        info.relColumns = relColumns;
        printData.previewData = info;
        printData.editorShow = 'preview';
      };

      //自动填充纸张
      const fillPaper = () => {
        const columns = xTable.value.getColumns();
        if (columns.length <= 0) {
          return Modal.alert('请导入字段！', 'error');
        }
        const newColumns = [];
        let sumUp = 0;
        columns.forEach((col) => {
          sumUp += col.renderWidth;
          newColumns.push({ field: col.field, width: col.renderWidth, title: col.title });
        });
        if (sumUp < printData.viewData.width - 36) {
          const width =
            printData.viewData.width - 36 - sumUp + columns[columns.length - 1].renderWidth;
          newColumns[newColumns.length - 1].width = width;
          printData.showColumn = newColumns;
          // xTable.value.refreshColumn();
          xTable.value.loadColumn(newColumns);
          // console.log(newColumns);
        }
      };

      //点击字段调整的menuItem
      const clickMenuItem = (item) => {
        item.checked = !item.checked;
        if (printData.showColumn.length <= 0 && item.checked) {
          printData.showColumn.push(item);
        } else {
          const columns = [];
          printData.showColumn = [];
          printData.tableColumn.forEach((record) => {
            if (record.checked) {
              columns.push(record);
            }
          });
          printData.showColumn = columns;
        }
      };

      return {
        printData,
        modelRef,
        validateInfos,
        closeModal,
        openEditorModal,
        changePageSize,
        getColumns,
        importColumn,
        showColumn,
        printTableData,
        xTable,
        doSave,
        doPreview,
        fillPaper,
        visible: ref(false),
        clickMenuItem,
      };
    },
  });
</script>
<style lang="less" scoped>
  .list-print {
    height: 100%;
    .print-default {
      background: #f2f2f2;
      border-bottom: 1px solid #e6e6e6;
      border-top: 1px solid #e6e6e6;
      display: flex;
      .print-default-view {
        background: #ffffff;
        margin: auto;
        .print-header {
          // height: 40px;
          line-height: 40px;
          text-align: left;
          padding: 0 18px;
        }
        .print-table {
          height: 80px;
          line-height: 80px;
          position: relative;
          margin: 0 18px;
          .je-grid {
            position: absolute;
            top: 20px;
            height: 40px;
            .vxe-table--empty-placeholder {
              display: none !important;
            }
          }
        }
        .print-fotter {
          // height: 40px;
          line-height: 40px;
          text-align: left;
          padding: 0 18px;
        }
      }
    }
    .print-bottom {
      .print-bottom-context {
        background: #faf9da;
        height: 40px;
        line-height: 40px;
        padding: 0px 18px;
        color: #d7a100;
      }
    }
  }
</style>
<style lang="less">
  .list-print {
    .print-table {
      .je-grid {
        .vxe-table--empty-placeholder {
          display: none !important;
        }
        .vxe-table--body-wrapper.body--wrapper {
          display: none !important;
        }
      }
    }
  }
</style>
